package cn.alex.sso.project.service.impl;

import cn.alex.sso.project.entity.SysClientSyncModule;
import cn.alex.sso.project.entity.SysClientSyncUrl;
import cn.alex.sso.project.entity.dto.SysClientDataSyncDto;
import cn.alex.sso.project.entity.params.SaveSysClientDataSync;
import cn.alex.sso.project.mapper.SysClientSyncModuleMapper;
import cn.alex.sso.project.mapper.SysClientSyncUrlMapper;
import cn.alex.sso.project.service.SysClientSyncService;
import cn.alex.sso.project.sync.DataSyncModuleService;
import cn.alex.sso.project.sync.entity.DataSyncEntity;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Alex
 * @description 针对表【sys_client_sync(应用同步设置表)】的数据库操作Service实现
 * @createDate 2024-12-04 13:10:33
 */
@Service
@RequiredArgsConstructor
public class SysClientSyncServiceImpl implements SysClientSyncService {
    private final SysClientSyncUrlMapper clientSyncUrlMapper;
    private final SysClientSyncModuleMapper clientSyncModuleMapper;
    private final DataSyncModuleService dataSyncModuleService;

    @Override
    public SaveSysClientDataSync getInfo(Long clientId) {
        SaveSysClientDataSync result = new SaveSysClientDataSync();
        result.setClientId(clientId);

        // 获取系统中的模块及模块类型
        List<SysClientDataSyncDto> data = new ArrayList<>();
        List<Map<String, Object>> info = dataSyncModuleService.getInfo();
        for (Map<String, Object> item : info) {
            data.add(new SysClientDataSyncDto(
                    new ArrayList<>(),
                    MapUtil.get(item, "module", DataSyncEntity.class),
                    MapUtil.get(item, "triggerList", List.class)
            ));
        }
        result.setData(data);


        // 获取当前应用的同步URL
        SysClientSyncUrl clientSyncUrl = clientSyncUrlMapper.selectById(clientId);
        if (ObjUtil.isEmpty(clientSyncUrl)) {
            return result;
        }
        result.setSyncUrl(clientSyncUrl.getSyncUrl());


        // 获取当前应用已经设置的同步模块及模块类型
        List<SysClientSyncModule> moduleList = clientSyncModuleMapper.selectList(new LambdaUpdateWrapper<SysClientSyncModule>().eq(SysClientSyncModule::getClientId, clientId));
        Map<String, List<SysClientSyncModule>> moduleListGroup = moduleList.stream().collect(Collectors.groupingBy(SysClientSyncModule::getSyncModule));

        for (SysClientDataSyncDto item : data) {
            String value = item.getModule().getValue();
            if (ObjUtil.isNotEmpty(moduleListGroup.get(value))) {
                item.setCheckedTriggerList(moduleListGroup.get(value).stream().map(SysClientSyncModule::getTriggerCondition).collect(Collectors.toList()));
            }
        }
        result.setData(data);

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SaveSysClientDataSync entity) {
        Long clientId = entity.getClientId();

        // 当前应用的同步URL
        clientSyncUrlMapper.insertOrUpdate(new SysClientSyncUrl(clientId, entity.getSyncUrl()));

        // 设置的同步模块及模块类型
        clientSyncModuleMapper.delete(new LambdaUpdateWrapper<SysClientSyncModule>().eq(SysClientSyncModule::getClientId, clientId));
        List<SysClientDataSyncDto> data = entity.getData();
        for (SysClientDataSyncDto item : data) {
            String value = item.getModule().getValue();
            List<String> checkedTriggerList = item.getCheckedTriggerList();
            for (String t : checkedTriggerList) {
                clientSyncModuleMapper.insert(new SysClientSyncModule(clientId, value, t));
            }
        }
    }


    @Override
    public List<SysClientSyncUrl> getNeedSyncClient(List<Long> clientId, String module, String trigger) {
        List<SysClientSyncModule> clientSyncModules = clientSyncModuleMapper.selectList(new LambdaUpdateWrapper<SysClientSyncModule>()
                .in(CollUtil.isNotEmpty(clientId), SysClientSyncModule::getClientId, clientId)
                .eq(SysClientSyncModule::getSyncModule, module)
                .eq(SysClientSyncModule::getTriggerCondition, trigger)
        );

        if (CollUtil.isEmpty(clientSyncModules)) {
            return null;
        }

        return clientSyncUrlMapper.selectList(new LambdaQueryWrapper<SysClientSyncUrl>()
                .in(SysClientSyncUrl::getClientId, clientSyncModules.stream().map(SysClientSyncModule::getClientId).collect(Collectors.toList()))
                .isNotNull(SysClientSyncUrl::getSyncUrl)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByClientId(Long clientId) {
        clientSyncUrlMapper.delete(new LambdaUpdateWrapper<SysClientSyncUrl>().eq(SysClientSyncUrl::getClientId, clientId));
        clientSyncModuleMapper.delete(new LambdaUpdateWrapper<SysClientSyncModule>().eq(SysClientSyncModule::getClientId, clientId));
    }
}




